package com.lemurian.bankdata.action.base;

import org.springframework.beans.factory.annotation.Autowired;

import com.lemurian.bankdata.dto.LogHelper;
import com.lemurian.bankdata.lite.authentication.BankDataPrincipal;
import com.lemurian.bankdata.lite.enums.UserActivityType;
import com.lemurian.bankdata.lite.logger.BankDataLogger;
import com.lemurian.bankdata.lite.utils.Encryption;
import com.lemurian.bankdata.lite.utils.GeneralConstant;
import com.lemurian.bankdata.lite.utils.GlobalFunction;
import com.lemurian.bankdata.services.ActivityLogService;
import com.lemurian.bankdata.services.UserService;
import com.lemurian.bankdata.utils.BaseAction;
import com.lemurian.entity.User;
import com.opensymphony.xwork2.Preparable;

public class ChangePasswordAction extends BaseAction implements Preparable {

	private static final long serialVersionUID = 1L;

	private BankDataLogger log = BankDataLogger.getLogger(HomeAction.class.getSimpleName());

	private BankDataPrincipal principal;
	private User user;
	
	private String oldPassword = "";
    private String newPassword = "";
    private String confirmPassword = "";
    
    private String jsonMessage = "", jsonType = "";
	
    @Autowired
    private UserService userService;
    
    @Autowired 
	private ActivityLogService userActivityLogService;
	private LogHelper userActivityLog;
	
	@Override
	public void prepare() throws Exception {
		principal = (BankDataPrincipal) getSession().get(GeneralConstant.USER_PRINCIPAL);
		user = principal.getUser();
	}
	
	public String formPassword() {
		log.info("User in change password form");

		setPreviousPage("formPassword");
        setMappedRequest("update");
		return SUCCESS;
	}
	
	@Override
	public String update() {
		setPreviousPage("formPassword");
        try {
            //activityLog = customerActivityBean.startActivity(customer, WalletActivityTypes.CHANGE_CUSTOMER_USER_PASSWORD, getRequest().getSession().getId());
        	
        	oldPassword = oldPassword.trim();
            oldPassword = Encryption.SHA1(oldPassword);
            
            if(!user.getPassword().equalsIgnoreCase(oldPassword)) {
                log.info("Invalid old password");
                jsonMessage = "Invalid old password";
                addCustomActionError(jsonMessage);
                setMappedRequestFullPath("/ChangePasswordAction_formPassword.do");
        		return GeneralConstant.REDIRECT;
            }

            if(newPassword.length() <8) {
                log.info("Minimum length password is 8");
                jsonMessage = "Minimum length password is 8";
                addCustomActionError(jsonMessage);
                setMappedRequestFullPath("/ChangePasswordAction_formPassword.do");
        		return GeneralConstant.REDIRECT;
            }

            if(!confirmPassword.equalsIgnoreCase(newPassword)) {
                log.info("Confirm password doesn't match");
                jsonMessage = "Confirm password doesn't match";
                addCustomActionError(jsonMessage);
                setMappedRequestFullPath("/ChangePasswordAction_formPassword.do");
        		return GeneralConstant.REDIRECT;
            }

            newPassword = Encryption.SHA1(newPassword.trim());

            if(newPassword.equalsIgnoreCase(user.getPassword1())
                || newPassword.equalsIgnoreCase(user.getPassword2())
                || newPassword.equalsIgnoreCase(user.getPassword3())
                || newPassword.equalsIgnoreCase(user.getPassword4())
                || newPassword.equalsIgnoreCase(user.getPassword5())) {

                log.info("New password has ever been used");
                jsonMessage = "New password has ever been used";
                addCustomActionError(jsonMessage);
                setMappedRequestFullPath("/ChangePasswordAction_formPassword.do");
        		return GeneralConstant.REDIRECT;
            }

            user.setPassword5(user.getPassword4());
            user.setPassword4(user.getPassword3());
            user.setPassword3(user.getPassword2());
            user.setPassword2(user.getPassword1());
            user.setPassword1(user.getPassword());

            user.setPassword(newPassword);
            try {
                user.setPasswordValidDate(GlobalFunction.passwordValidDate(user.getPasswordValidDate()));
            } catch(Exception e) {
                log.info("Error add 90 day from old user password valid date : "+e.getMessage());
                e.printStackTrace();
            }

            try {
                userService.save(user);

                setPrincipal((BankDataPrincipal) getSession().get(GeneralConstant.USER_PRINCIPAL));
                getPrincipal().setUser(user);
                getSession().put(GeneralConstant.USER_PRINCIPAL, getPrincipal());
                
                log.info("Password has been updated");
                jsonMessage = "Password has been updated";
                
                addCustomActionMessage(jsonMessage);
                
                    
            } catch (Exception e) {
                e.printStackTrace();
            }

            
            userActivityLog = new LogHelper(user, UserActivityType.CHANGE_PASSWORD);
			
            try {
                log.sInfo(" :: User [%s:%s] is successfully changed his/her password", user.getId(), user.getName());

                //check if activity is success
                userActivityLog.setStatus(LogHelper.SUCCESS_ACTIVITY);
            } catch (Exception e) {
                log.sInfo(" :: Error was raised when User [%s:%s] change his/her password", user.getId(), user.getName());
                
                //set activity log status into failed
                userActivityLog.setStatus(LogHelper.FAILED_ACTIVITY);
                userActivityLog.setErrorMsg(e.getMessage());
            }
            //save activity log
            userActivityLog.getAdditionalParams().add(user.getName());
            userActivityLogService.saveUserActivity(userActivityLog);
            
            setMappedRequestFullPath("/ChangePasswordAction_formPassword.do");
    		return GeneralConstant.REDIRECT;
    		
        } catch (Exception ex) {
            log.sInfo("Error : %s", ex.getMessage());
        }
		return GeneralConstant.JSON;
	}
	
	@Override
	public String add() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String delete() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String detail() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String edit() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String list() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String save() {
		// TODO Auto-generated method stub
		return null;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public BankDataPrincipal getPrincipal() {
		return principal;
	}

	public void setPrincipal(BankDataPrincipal principal) {
		this.principal = principal;
	}

	public String getOldPassword() {
		return oldPassword;
	}

	public void setOldPassword(String oldPassword) {
		this.oldPassword = oldPassword;
	}

	public String getNewPassword() {
		return newPassword;
	}

	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}

	public String getConfirmPassword() {
		return confirmPassword;
	}

	public void setConfirmPassword(String confirmPassword) {
		this.confirmPassword = confirmPassword;
	}

	public String getJsonMessage() {
		return jsonMessage;
	}

	public void setJsonMessage(String jsonMessage) {
		this.jsonMessage = jsonMessage;
	}

	public String getJsonType() {
		return jsonType;
	}

	public void setJsonType(String jsonType) {
		this.jsonType = jsonType;
	}
	
}